<template>
  <div class="order-list-container">
    <!-- 订单列表表单项 -->
    <el-card class="order-card" shadow="never">
      <el-form :inline="true" label-position="right" label-width="85px" :model="orderOptions" size="small" ref='orderOptions' class="demo-form-inline order-form">
        <el-form-item label="订单号：" prop="orderId">
          <el-input v-model="orderOptions.orderId" placeholder="请输入精准订单号" suffix-icon="xxxx"></el-input>
        </el-form-item>
        <el-form-item label="订单状态：" prop="orderPayFlag">
          <el-select v-model="orderOptions.orderPayFlag" clearable placeholder="全部状态">
            <el-option label="全部状态" :value="''"></el-option>
            <el-option v-for="(value, key) in orderPayFlags" :label="value" :value="Number(key)" :key="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="油站：" class="order-options-item" prop="gasId">
          <el-select v-model="orderOptions.gasId" clearable placeholder="全部油站" >
            <el-option label="全部油站" :value="''">
            </el-option>
            <el-option v-for="item in gasList" :label="item.gasName"  :value="item.gasId" :key="item.gasId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="枪号：" prop="gunNo">
          <el-input  v-model="orderOptions.gunNo" placeholder="请输入数字" suffix-icon="xxxx" clearable></el-input>
        </el-form-item>
        <el-form-item label="油号：" prop="oilNo">
          <el-select v-model="orderOptions.oilNo" clearable placeholder="请选择油号">
            <el-option label="请选择油号" :value="''"></el-option>
            <el-option v-for="item in oilNumList" :label="item.oilNum" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间：">
          <el-date-picker
            v-model="payTime"
            :default-time="['00:00:00', '23:59:59']"
            type="datetimerange"
            unlink-panels
            align="right"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="onChangePayTime">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="g-flex-c">
        <el-button class="btn" style="width: 70px;" size="mini" type="primary" @click="query('check')">查询</el-button>
        <el-button style="width: 70px" size="mini" @click="resetForm" >重置</el-button>
        <el-button style="width: 70px" size="mini" @click="onExportExcel">导出</el-button>
      </div>
    </el-card>
    <!-- 订单列表汇总项 -->
    <el-card class="order-card"  v-loading="isAllLoading" shadow="never">
      <div class="card">
        <card title="交易总金额" width="25%" unit="元" :num="allNumber.allGunAmount | formatMoney" back='linear-gradient(225deg, #81A5FF 0%, #4B7EFE 100%)' :img="`${$ossUrl}market/effect-head.png`"/>
        <card title="订单数量" width="25%" unit="单" :num="allNumber.orderTotal | formatMoney" back='linear-gradient(225deg, #ECD39E 0%, #D6A75B 100%)' :img="`${$ossUrl}market/effect-file.png`"/>
        <card title="总升数" width="25%" unit="升" :num="allNumber.allLitre | formatMoney" back='linear-gradient(225deg, #B3B2DA 0%, #7578B4 100%)' :img="`${$ossUrl}market/effect-folder.png`"/>
      </div>
    </el-card>
    <!-- 订单列表表格 -->
    <el-card class="order-card drawer-tabel"  :body-style="{ padding: '0' }" shadow="never">
      <el-table v-loading="loading" height="500px"  size="small" :data="orderData"  highlight-current-row stripe style="width: 100%">
        <template v-for="(item,index) in tableConfig" >
          <el-table-column v-if="item.slot === 'action'" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'> 
            <template slot-scope="scope">
              <el-button-group>
                <el-button class="sm-btn default" size="mini" @click="showDetail(scope.row)">详情</el-button>
                <template  v-if="scope.row.orderPayFlag === 1">
                  <el-button size="mini" class="sm-btn" @click="showRefund(scope.row)">申请退款</el-button>
                  <el-button size="mini" class="sm-btn" @click="showDoc(scope.row.orderId)">补打小票</el-button>
                </template>
              </el-button-group>
            </template>
          </el-table-column>
          <el-table-column v-else :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'></el-table-column>
        </template>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageOptions.pageIndex"
          :page-sizes="pageSizes"
          :page-size="pageOptions.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="allTotal">
        </el-pagination>
      </div>
    </el-card>
    <!-- 退款弹窗 -->
    <el-dialog center :visible.sync="isShowDialog">
      <div slot="title">退款原因</div>
      <el-form ref="refund" :rules="refundRules" :model="refundOptions" label-width="90px" size="mini">
        <el-form-item label="退款金额:">
          <div>{{'¥'+refundOptions.amountGun}}</div>
        </el-form-item>
        <el-form-item label="订单编号:">
          <div>{{refundOptions.orderId}}</div>
        </el-form-item>
        <el-form-item label="退款原因:(必选)" prop="refundType">
          <el-select v-model="refundOptions.refundType" size="middle" style="width:420px" placeholder="请选择退款原因">
            <el-option v-for="(item,index) in reasonList" :key="index" :label="item" :value="index"></el-option>
          </el-select>
         </el-form-item>
        <el-form-item prop="remark" >
          <el-input
            v-if="refundOptions.refundType === '999'"
            type="textarea"
            :rows="7"
            :placeholder="refundOptions.refundType !== '999' ? '请填写退款原因' : '5-200个字，必填 请您补充详细退款原因能够提高退款时效哦~'"
            minlength="5"
            maxlength="200"
            v-model="refundOptions.remark"
            class="text-area"
            style="width:420px"
            @submit.native.prevent>
          </el-input>
        </el-form-item>
      </el-form>   
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDailog(0)">取 消</el-button>
        <el-button type="primary"  @click="closeDailog(1)">确认申请</el-button>
      </div>
    </el-dialog>
    <!-- 订单详情组件 -->
    <orderDetail ref="orderDetail" :orderId="orderId"></orderDetail>
    <!-- 补打小票提示 -->
    <el-dialog
      top="30vh"
      title="提示"
      :visible.sync="isShowTicket"
      width="30%"
      center>
      <div style="width: 100%;text-align: center">确认补打小票？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowTicket = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleTicket">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryOrderList, submitRefund, makeSmallTicket, exportData, getQueryOrderType, getQueryGasList, getOilNumList, getSum } from '@/api/order/posOrder'
import { getRefundReason } from '@/api/order'
import { exportSearchList } from '@/utils/listTools'
import orderDetail from './orderDetail'
import card from '@/components/work/card'
import moment from 'moment'
import _ from 'lodash'

const TABLECONFIG = [
  {label: '订单号',prop: 'orderId'},
  {label: '加油金额',prop: 'amountGun'},
  {label: '枪号',prop: 'gunNo'},
  {label: '油号',prop: 'oilNumName'},
  {label: '升数',prop: 'litre'},
  {label: '订单状态',prop: 'orderPayFlagName'},
  {label: '支付时间',prop: 'payDt'},
  {label: '所属油站',prop: 'gasName'},
  {label: '操作' , slot: "action", width: 330, fixed: "right"}
]

export default {
  components: {
    orderDetail,
    card
  },
  data () {
    return {
      tableConfig: TABLECONFIG,
      isShowTicket: false,
      orderId: '', // 查看详情使用
      isShowDialog: false,
      refundOptions: { // 退款选项
        refundType: '',
        amountGun: '',
        orderId: '',
        remark: ''
      },
      reasonList: [],
      isAllLoading: false,
      loading: false,
      btnLoading: false,
      pageSizes: [20], // 每页展示选项
      orderData: [], // 订单列表
      orderOptions: {
        gasId: '', // 油站id
        orderPayFlag: '', // 订单状态
        orderId: '', // 订单号
        gunNo: '', // 枪号
        oilNo: '', // 油号
        payDtStart: '', // 选择起始时间
        payDtEnd: '' // 选择终止时间
      },
      pageOptions: {
        pageIndex: 1, // 当前页
        pageSize: 20 // 每页个数
      },
      saveOptions:{},
      allTotal: 0,
      gasList: [], // 油站名称列表
      orderPayFlags: {}, // 订单状态列表
      oilNumList: {}, // 油号列表
      payTime: [], // 初始时间展示
      allNumber: {
        allGunAmount: '', // 交易总金额 
        allPayAmount: '', // 实付总金额
        orderTotal: '', // 订单总单数
        allLitre: '', // 升数总和
      },
    }
  },
  async mounted () {
    this.resetDate()
    this.saveOptions = {...this.orderOptions}
    this.init()
    this.initRefundReason()
  },
  computed: {
    refundRules () {
      return {
        refundType: [
          { required: true, message: '请选择退款原因', trigger: 'change' }
        ],
        remark: [
           { required: this.isOther, message: '请补充详细退款原因', trigger: 'blur' },
           { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
        ]
      }
    },
    isOther () {
      return this.refundOptions.refundType === '999'
    }
  },
  methods: {
    resetDate () {
      this.payTime = [moment().format("YYYY-MM-DD 00:00:00"), moment().format("YYYY-MM-DD HH:mm:ss")]
      this.orderOptions.payDtStart = moment().format("YYYY-MM-DD 00:00:00")
      this.orderOptions.payDtEnd = moment().format("YYYY-MM-DD HH:mm:ss")
    },
    resetForm () {
      this.orderOptions = {
        gasId: '', // 油站id
        orderPayFlag: '', // 订单状态
        orderId: '', // 订单号
        gunNo: '', // 枪号
        oilNo: '', // 油号
        payDtStart: '', // 选择起始时间
        payDtEnd: '' // 选择终止时间
      },
      this.resetDate()
      this.pageOptions.pageIndex = 1
      this.pageOptions.pageSize = 20
      this.initContent()
    },
    closeDailog (type) {
      if (type) { // 点击确认
        this.$refs.refund.validate((vaild) => {
          if (vaild) {
            this.submitRefund()
          } else {
            return false
          }
        })
      } else {
        this.refundOptions = {
          refundType: '',
          amountGun: '',
          orderId: '',
          remark: ''
        }
        this.isShowDialog = false
      }
      
    },
    async submitRefund () { // 提交退款信息
      let params = { ...this.refundOptions }
      delete params.amountGun
      try {
        const { code, message } = await submitRefund(params)
        code === 200 ? this.$message.success('退款成功') : this.$message.error(message)
      } catch (error) {
        console.log(error.message)
      } finally {
        this.initContent()
        this.refundOptions = {
          refundType: '',
          amountGun: '',
          orderId: '',
          remark: ''
        }
        this.isShowDialog = false
      } 
    },
    async getSum () { // 获取总数据
      let params = {...this.orderOptions, ...this.pageOptions}
      this.isAllLoading = true
      try {
        const { code, result } = await getSum(params)
        if (code !== 200) return
        this.allNumber = result
      } catch (error) {
        console.log(error.message)
      } finally {
        this.isAllLoading = false
      }
    },
    init () { // 初始化页面
      this.getQueryOrderType()
      this.getQueryGasList()
      this.getOilNumList()
      this.initContent()
    },
    initContent () { // 获取订单数据
      this.queryOrderList()
      this.getSum()
    },
    handleSizeChange (val) {
      console.log(val) // 每页显示多少条改变时触发
    },
    handleCurrentChange (val) {
      this.pageOptions.pageIndex = val
      this.queryOrderList(false, true)
    },
    showDetail (row) { // 查看订单详情
      this.$refs.orderDetail.isShowDetail = true
      this.$refs.orderDetail.getOrderDetail(row)
    },
    showRefund (item) { // 展示申请退款
      const { amountGun, orderId } = item
      this.refundOptions = {
        amountGun,
        orderId,
        refundType: '',
        remark: ''
       }
      this.isShowDialog = true
    },
    showDoc (orderId) { // 补打小票
      this.orderId = orderId
      this.isShowTicket = true
    },
    async handleTicket () { // 处理补打小票
      try {
        this.btnLoading = true
        const { code } = await makeSmallTicket({
          orderId: this.orderId
        })
        if (code !== 200) return
        this.$message.success('补打小票成功')
      } catch (error) {
        console.log(error.message)
      } finally {
        this.btnLoading = false
        this.isShowTicket = false
        this.initContent()
      }
    },
    query: _.throttle(function (type) { // 点击查询
      let { orderId, gunNo } = this.orderOptions
      if (orderId && !(/^[0-9a-zA-Z]*$/.test(orderId))) {
        this.$message.error('请输入正确的订单号')
        return
      }
      if (gunNo && !(/^[1-9]\d{0,1}$/.test(gunNo))) {
        this.$message.error('请输入正确的油枪号')
        return
      }
      if (type) {
        this.pageOptions.pageIndex = 1
        this.pageOptions.pageSize = 20
      }
      this.queryOrderList(type)
      this.getSum()
    }, 1000),
    async queryOrderList (type, change) { // 获取订单列表
      if (change) {
        this.orderOptions = { ...this.saveOptions }
        let { payDtStart, payDtEnd } = this.saveOptions
        this.payTime = [payDtStart, payDtEnd]
      }
      this.loading = true
      let params = {...this.orderOptions, ...this.pageOptions}
      try {
        const { code, result, totalRow } = await queryOrderList(params)
        if (code !== 200) return
        if (type) this.saveOptions = {...this.orderOptions}
        this.orderData = result ? result : []
        this.allTotal = totalRow
      } catch (error) {
        console.log(error.message)
      } finally {
        this.loading = false
      }  
    },
    onChangePayTime (val) {
      if(!val) {
        this.orderOptions.payDtStart = ''
        this.orderOptions.payDtEnd = ''
        this.payTime = []
        return
      }
      if((moment(val[1]).valueOf() - moment(val[0]).valueOf()) > 3600 * 1000 * 24 * 59) {
        this.orderOptions.payDtStart = ''
        this.orderOptions.payDtEnd = ''
         this.payTime = []
        this.$message.info('选择时间段不能超过60天')
        return
      }
      this.orderOptions.payDtStart = val[0]
      this.orderOptions.payDtEnd = val[1]
    },
    async onExportExcel () {
      let length = this.orderData.length
      if (!length) {
        this.$message.error('导出excel为空，不能导出')
        return
      }
      try {
        const { code, result = {} } = await exportData(this.saveOptions)
        if (code !== 200) return
        // const time = moment().format("YYYY-MM-DD")
        // const name = `订单列表_${time}`
        exportSearchList(result.file, result.fileName)
      } catch (error) {
        console.log(error.message)
      }
    },
    async getQueryOrderType () { // 获取订单查询订单状态
      try {
        const { code, result } = await getQueryOrderType()
        if (code !== 200) return
        this.orderPayFlags = result || {}
      } catch (error) {
        console.log(error.message)
      }
    },
    async getQueryGasList () { // 获取订单查询油站信息
      try {
        const { code, result } = await getQueryGasList()
        if (code !== 200) return
        this.gasList = result || []
      } catch (error) {
        console.log(error.message)
      }
    },
    async getOilNumList () { // 获取油号列表
      try {
        const { code, result } = await getOilNumList()
        if (code !== 200) return
        this.oilNumList = result || []
      } catch (error) {
        console.log(error.message)
      }
    },
    async initRefundReason () {
      try {
        const { code, result } = await getRefundReason()
        if (code !== 200) return
        this.reasonList = result
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url('../styles/orderList.less');
</style>
